<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <button>获取商品</button>

        <script>
            function sendAJAX(type, url) {
                // 发送请求,  返回 promise 对象
                return new Promise((resolve, reject) => {
                    //发送请求
                    let xhr = new XMLHttpRequest();
                    xhr.responseType = "json";
                    //
                    xhr.open(type, url);
                    //
                    xhr.send();
                    //
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            if (xhr.status >= 200 && xhr.status < 300) {
                                //成功
                                resolve({
                                    status: xhr.status,
                                    statusText: xhr.statusText,
                                    headers: xhr.getAllResponseHeaders(),
                                    data: xhr.response,
                                    request: xhr
                                });
                            } else {
                                //失败
                                reject(xhr.status);
                            }
                        }
                    };
                });
            }

            let btn = document.querySelector("button");

            btn.onclick = async function () {
                try {
                    let data = await sendAJAX(
                        "get",
                        "https://api.xiaohigh.com/goods"
                    );
                    console.log(data);
                } catch (e) {
                    console.log(e);
                }
            };
        </script>
    </body>
</html>
